package cn.pconline.autoclub.service;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Activity;
import cn.pconline.autoclub.entity.ActivityContext;
import cn.pconline.autoclub.entity.ActivityDiary;
import cn.pconline.autoclub.entity.ActivityMember;
import cn.pconline.autoclub.entity.ActivityTopic;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubForum;
import cn.pconline.autoclub.entity.ClubIntegral;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.r.client.EntityBuilder;
import cn.pconline.r.client.ResponseExtractor;
import cn.pconline.r.client.SimpleHttpTemplate;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;
import org.gelivable.dao.GeliDao;
import org.gelivable.dao.GeliOrm;
import org.gelivable.dao.SqlBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * @author 作者 guoqiang
 * @version 2014-1-21
 */
public class ActivityService {

    @Autowired
    GeliDao geliDao;
    @Autowired
    GeliOrm geliOrm;
    @Autowired
    private PagerService pagerService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private PetrolService petrolService;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    private SimpleHttpTemplate simpleHttpTemplate;
    @Autowired
    private ClubService clubService;
    @Autowired
    private IntfService intfService;
    @Autowired
    private UserService userService;
    @Autowired
    private DynaService dynaService;
    
    private static final Logger log = LoggerFactory.getLogger(ActivityService.class);

    /**
     * 活动创建
     *
     * @param activity
     */
    public long createActivity(Activity activity) {
        int longMessage = 0;
        String message = activity.getContext();
        if (message.length() > 255) {
            longMessage = 1;

            activity.setContext(message.substring(0, 255));
        }
        activity.setLongContext(longMessage);
        long id = geliDao.create(activity);
        if (longMessage == 1) {
            createAutoSaveText(activity.getActivityId(), message);
        }
        
        return id;
    }

    /**
     * 同步到所选中的论坛
     *
     * @param activity
     * @param fids 需要同步的fid
     */
    public void syncBbsCreateTopic(Activity activity, Set<Long> fids) {
        //同步论坛
        Club club = clubService.getClub(activity.getClubId());
        ClubMember member = memberService.find(activity.getCreateBy());
        List<ClubForum> forums = clubService.getForumList(activity.getClubId());
        if (forums != null && !forums.isEmpty()) {
            for (ClubForum f : forums) {
                if (fids.contains(f.getForumId())) {
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("fid", f.getForumId());
                    params.put("uid", member.getUid());
                    params.put("content", activity.getFullContent()
                            + "\n[url=" + systemConfig.getRoot()
                            + "/" + club.getClubUrl() + "/activity/a"
                            + activity.getActivityId() + "/]点击报名[/url]");
                    params.put("title", "【" + club.getName() + "】" + activity.getTitle());
                    String result = sendToBBS(params);
                    //解析结果
                    try {
                        JSONObject bbsJson = JSONObject.parseObject(result);
                        if (bbsJson != null && bbsJson.getIntValue("status") == 0) {
                            long tid = bbsJson.getLongValue("topicId");
                            if (tid > 0L) {
                                ActivityTopic activityTopic = new ActivityTopic();
                                activityTopic.setActivityId(activity.getActivityId());
                                activityTopic.setFormumId(f.getForumId());
                                activityTopic.setTopicId(tid);
                                geliDao.create(activityTopic);
                            }
                        }
                    } catch (Exception e) {
                        log.error("解析论坛poster.jsp的返回JSON对象出错:" + result);
                    }
                }
            }
        }
    }

    /**
     * 活动修改
     *
     * @param activity
     */
    public void updateActivity(Activity activity) {
        int longMessage = 0;
        String message = activity.getContext();
        int oldLongMessage = activity.getLongContext();
        if (message.length() > 255) {
            longMessage = 1;
            activity.setContext(message.substring(0, 255));
        }
        activity.setLongContext(longMessage);
        geliDao.update(activity);
        if (oldLongMessage > 0) {
            //删除旧的超长内容
            this.removeAcLongContext(activity.getActivityId());
        }
        if (longMessage == 1) {
            createAutoSaveText(activity.getActivityId(), message);
        }

        Club club = clubService.getClub(activity.getClubId());
        //同步论坛
        List<ActivityTopic> activityTopics = listActivityTopic(activity.getActivityId());
        ClubMember member = memberService.find(activity.getCreateBy());
        if (activityTopics != null && !activityTopics.isEmpty()) {
            for (ActivityTopic topic : activityTopics) {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("tid", topic.getTopicId());
                params.put("uid", member.getUid());
                params.put("method", "update");
                params.put("content", message
                        + "\n[url=" + systemConfig.getRoot()
                        + "/" + activity.getClubId() + "/activity/a"
                        + activity.getActivityId() + "/]点击报名[/url]");
                params.put("title", "【" + club.getName() + "】" + activity.getTitle());
                String result = sendToBBS(params);

                try {
                    JSONObject bbsJson = JSONObject.parseObject(result);
                    if (bbsJson == null || bbsJson.getIntValue("status") != 0) {
                        log.error("同步到更新活动到论坛失败：" + result);
                    }
                } catch (Exception e) {
                    log.error("", e);
                }

            }
        }
    }

    /**
     * 内容截断分批插入数据库
     *
     * @param activityId
     * @param message
     */
    private int createAutoSaveText(long activityId, String message) {

        if (message.length() < 255) {
            return 0;
        }
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT INTO  ");
        sql.append(geliOrm.getTableName(ActivityContext.class, activityId));
        sql.append(" (context_id, activity_id, seq, content) value (?, ?, ?, ?)");

//        SqlBuilder maxSql = new SqlBuilder();
//        maxSql.appendSql(" select max(context_id) from ");
//        maxSql.appendSql(geliOrm.getTableName(ActivityContext.class, activityId));
//        
//        long maxId = jdbcTemplate.queryForLong(maxSql.getSql());
        //批量插入
        List<Object[]> batch = new ArrayList<Object[]>();
        for (int i = 255, n = 1, length = message.length(); i < length; i += 255, n++) {
            int j = Math.min(length, i + 255);
            Object[] values = new Object[]{geliDao.generateId(ActivityContext.class), activityId, n, message.substring(i, j)};
            batch.add(values);
        }

        return jdbcTemplate.batchUpdate(sql.toString(), batch).length;
    }

    /**
     * 根据车友会ID获取完整活动内容
     *
     * @param clubId
     * @return
     */
    public String getTotalActivityTxt(long activityId) {
        if (activityId < 1) {
            return null;
        }
        StringBuilder context = new StringBuilder("");
        Activity activity = geliDao.find(Activity.class, activityId);
        if (activity != null) {
            context.append(activity.getContext());
            if (activity.getLongContext() > 0) {
                SqlBuilder sql = new SqlBuilder();
                sql.appendSql(" select context_id from ").appendSql(geliOrm.getTableName(ActivityContext.class, activityId));
                sql.appendSql(" where activity_id = ").appendValue(activityId);
                sql.appendSql(" order by seq ");
                try {
                    List<ActivityContext> listTxt = geliDao.list(ActivityContext.class, activityId, sql.getSql(), sql.getValues());
                    if (listTxt != null && !listTxt.isEmpty()) {
                        for (ActivityContext ctxt : listTxt) {
                            context.append(ctxt.getContext());
                        }
                    }
                } catch (DataAccessException e) {
                    log.error("完整内容加载出错：" + sql.getSql() + "---" + activityId, e);
                }
            }
        }
        return context.toString();
    }

    /**
     * 活动列表
     *
     * @param clubId
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Pager<Activity> pageForList(long memberId, long clubId, boolean isStart, int pageNo, int pageSize) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select activity_id from ").appendSql(geliOrm.getTableName(Activity.class));
        if (clubId > 0) {
            sql.appendSql(" where club_id =").appendValue(clubId);
        }
        if (isStart) {
            sql.appendSql(" and now() <=begin_date ");
        }
        sql.appendSql(" and status = ").appendValue(Activity.STATUS_YES);
        sql.appendSql(" order by create_at desc");
        Pager<Activity> pager = pagerService.pager(Activity.class, sql, pageNo, pageSize);
        if (pager.getResultList() != null && !pager.getResultList().isEmpty()) {
            for (Activity activity : pager.getResultList()) {
            	//登录者的活动状态提示
                activity.setUserActivityStatus(this.getListActivityStatus(memberId, activity).get("code"));
                activity.setUserActivityStatusMsg(this.getListActivityStatus(memberId, activity).get("msg"));
                //创建者信息
                User createUser = userService.findUser(activity.getCreateBy());
                activity.setCreator(createUser);
                //活动报名列表
                Pager<ActivityMember> activityMemberPager = this.pageForApplyList(activity.getActivityId(), ActivityMember.STATUS_PASS, 1, 5);
                if(activityMemberPager != null && !activityMemberPager.getResultList().isEmpty()) {
                	List<ActivityMember> activityMembers = activityMemberPager.getResultList();
                	activity.setActivityMemberList(activityMembers);
                	//成功报名人数
                	activity.setApplyPassCount(activityMemberPager.getTotal());
                }

            }
        }
        return pager;
    }
    
    /**
     * 活动列表（不带用户相关的信息:如已报名，已过期。。）
     * @param clubId
     * @param isStart
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Pager<Activity> pageForList(long clubId,boolean isStart,int pageNo,int pageSize){
    	if(clubId<=0) return null;
    	SqlBuilder sql = new SqlBuilder();
    	sql.appendSql(" select activity_id from ").appendSql(geliOrm.getTableName(Activity.class));
    	sql.appendSql(" where club_id =").appendValue(clubId);
        if (isStart) {
            sql.appendSql(" and now() <=begin_date ");
        }
        sql.appendSql(" and status = ").appendValue(Activity.STATUS_YES);
        sql.appendSql(" order by create_at desc");
        Pager<Activity> pager = pagerService.pager(Activity.class, sql, pageNo, pageSize);
        return pager;
    }

    /**
     * 活动详情
     *
     * @param activityId
     * @return
     */
    public Activity findById(long activityId) {
        if (activityId < 1) {
            return null;
        }
        try {
            Activity a = geliDao.find(Activity.class, activityId);
            if (a.getStatus() == Activity.STATUS_YES) {
                return a;
            }
        } catch (EmptyResultDataAccessException e) {
        }
        return null;
    }

    /**
     * 根据活动ID获取参加人员
     *
     * @param activityId
     * @param clubId
     * @return
     */
    public List<ActivityMember> listMemberByActivitiId(long activityId, int status) {

        if (activityId <= 0) {
            return null;
        }
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select a.id FROM ac_activity_member a ,ac_member_info b , ac_activity c   WHERE ");
        sql.appendSql(" a.user_id  = b.id AND a.activity_id = c.activity_id AND b.club_id = c.club_id  ");
        sql.appendSql(" AND a.activity_id = ").appendValue(activityId);
        if (status != -99) {
            sql.appendSql(" AND a.status = ").appendValue(status);
        }
        sql.appendSql(" and c.status =").appendValue(Activity.STATUS_YES);
        List<ActivityMember> list = geliDao.list(ActivityMember.class, sql.getSql(), sql.getValues());
        if (list != null && !list.isEmpty()) {
            for (ActivityMember activitymember : list) {
                if (activitymember.getUserId() > 0) {
                    ClubMember clubMember = memberService.find(activitymember.getUserId());
                    if (clubMember != null) {
                        activitymember.setUserPic(WebUtils.face(clubMember.getUid(), 50));
                        activitymember.setUserUrl(systemConfig.getUcRoot() + "/" + clubMember.getUid() + "/");
                        activitymember.setUserWapUrl(systemConfig.getUcRoot() + "/my/" + clubMember.getUid() + "/");
                        activitymember.setUser(userService.findUser(clubMember.getUid()));
                    }
                }
            }
        }
        return list;
    }
    

    /**
     * 我参与的活动 userId：用户ID
     */
    public Pager<Activity> pageMyJoinActivity(long userId, long clubId, boolean isValid, int pageNo, int pageSize) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select activity.activity_id from ac_activity_member member ");
        sql.appendSql(" , ac_activity activity where  member.activity_id = activity.activity_id ");
        sql.appendSql(" and member.user_id in (").appendSql("SELECT id FROM ac_member_info WHERE user_id = ").appendValue(userId).appendSql(")");
        if (clubId > 0) {
            sql.appendSql(" and activity.club_id = ").appendValue(clubId);
        }
        if (isValid) {
            sql.appendSql(" and activity.status =").appendValue(Activity.STATUS_YES);
        }
        return pagerService.pager(Activity.class, sql, pageNo, pageSize);
    }

    public List<Activity> listActivityByUser(long userId, long clubId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select activity.activity_id from ac_activity activity, ac_activity_member member ");
        sql.appendSql("where member.activity_id = activity.activity_id ");
        sql.appendSql("and member.user_id in (select id from ac_member_info where user_id = ");
        sql.appendValue(userId).appendSql(")");
        sql.appendSql(" and activity.club_id = ").appendValue(clubId);
        sql.appendSql(" and activity.status = ").appendValue(Activity.STATUS_YES);
        try {
            return geliDao.list(Activity.class, sql.getSql(), sql.getValues());
        } catch (DataAccessException e) {
            return Collections.emptyList();
        }
    }

    /**
     * 热门活动 -->>>未结束的活动，按活动开始时间
     *
     * @param limit 取多少条，默认全部
     * @param isEnd 取未结束活动还是全是
     * @return
     */
    public List<Activity> listActivity(long memberId, long clubId, int limit, boolean isEnd, boolean isValid) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select activity_id from ac_activity where 1 =1 ");
        if (isEnd) {
            sql.appendSql(" and end_date >=NOW() ");
        }
        if (clubId > 0) {
            sql.appendSql(" and club_id = ").appendValue(clubId);
        }
        if (isValid) {
            sql.appendSql(" and status =").appendValue(Activity.STATUS_YES);
        }
        sql.appendSql(" order by create_at desc ");
        if (limit > 0) {
            sql.appendSql(" limit 0, " + limit);
        }
        List<Activity> list = geliDao.list(Activity.class, sql.getSql(), sql.getValues());
        if (list != null && !list.isEmpty()) {
            for (Activity activity : list) {
            	//登录者的活动状态提示
                activity.setUserActivityStatus(this.getListActivityStatus(memberId, activity).get("code"));
                activity.setUserActivityStatusMsg(this.getListActivityStatus(memberId, activity).get("msg"));
                //创建者信息
                User createUser = userService.findUser(activity.getCreateBy());
                activity.setCreator(createUser);
                //活动报名列表
                Pager<ActivityMember> activityMemberPager = this.pageForApplyList(activity.getActivityId(), ActivityMember.STATUS_PASS, 1, 5);
                if(activityMemberPager != null && !activityMemberPager.getResultList().isEmpty()) {
                	List<ActivityMember> activityMembers = activityMemberPager.getResultList();
                	activity.setActivityMemberList(activityMembers);
                	//成功报名人数
                	activity.setApplyPassCount(activityMemberPager.getTotal());
                }

            }
        }
        return list;
    }

    /**
     * 拿出该会员报名该活动的信息
     *
     * @param clubId
     * @param activityId
     * @param id
     * @return
     */
    public ActivityMember isSignUp(long activityId, long userId) {

        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select id from ac_activity_member where activity_id = ").appendValue(activityId);
        sql.appendSql(" and user_id = ").appendValue(userId);
        List<ActivityMember> list = geliDao.list(ActivityMember.class, sql.getSql(), sql.getValues());
        ActivityMember activityMember = null;
        if (list != null && !list.isEmpty()) {
            activityMember = list.get(0);
        }
        return activityMember;
    }

    /**
     * 取消报名
     *
     * @param activityMemberId
     */
    public int deleteActityMember(long activityId, long memberId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" delete from ac_activity_member where activity_id = ? and user_id =?");
        return jdbcTemplate.update(sql.getSql(), activityId, memberId);
    }

    /**
     * 退出车友会之后删除活动报名记录
     *
     * @param userId
     * @return
     */
    public int deleteActityMember(long userId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" delete from ac_activity_member where user_id = ").appendValue(userId);
        return jdbcTemplate.update(sql.getSql(), sql.getValues());
    }

    /**
     * 活动报名
     *
     * @param activityMemberId
     */
    public long createActityMember(ActivityMember activityMember) {
        return geliDao.create(activityMember);
    }

    /**
     * 活动日记列表
     *
     * @param activityId
     * @return
     */
    public Pager<ActivityDiary> pageActivityDiary(long activityId, long clubId, int pageNo, int pageSize) {

        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select diary_id from ac_activity_diary where 1 = 1 ");
        if (activityId > 0) {
            sql.appendSql(" and activity_id = ").appendValue(activityId);
        }
        if (clubId > 0) {
            sql.appendSql(" and club_id = ").appendValue(clubId);
        }
        sql.appendSql(" order by begin_at desc ");
        return pagerService.pager(ActivityDiary.class, sql, pageNo, pageSize);
    }

    /**
     * 活动日记列表
     *
     * @param activityId
     * @return
     */
    public List<ActivityDiary> listActivityDiary(long activityId, long clubId, int limit) {

        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select diary_id from ac_activity_diary where 1 = 1 ");
        if (activityId > 0) {
            sql.appendSql(" and activity_id = ").appendValue(activityId);
        }
        if (clubId > 0) {
            sql.appendSql(" and club_id = ").appendValue(clubId);
        }
        sql.appendSql(" order by begin_at desc ");
        if (limit != 99) {
            sql.appendSql(" LIMIT " + limit);
        }
        return geliDao.list(ActivityDiary.class, sql.getSql(), sql.getValues());
    }

    /**
     * 分页获取活动日记列表
     *
     * @param activityId
     * @return
     */
    public Pager<ActivityDiary> pagerActivityDiary(long activityId, long clubId, int pageNo, int pageSize) {

        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select diary_id from ac_activity_diary where 1 = 1 ");
        if (activityId > 0) {
            sql.appendSql(" and activity_id = ").appendValue(activityId);
        }
        if (clubId > 0) {
            sql.appendSql(" and club_id = ").appendValue(clubId);
        }
        sql.appendSql(" order by begin_at desc ");
        return pagerService.pager(ActivityDiary.class, sql, pageNo, pageSize);
    }

    /**
     * 根据活动ID统计活动日记篇数
     *
     * @param activityId
     * @return
     */
    public int countDiayByActivityId(long activityId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select count(1) from ac_activity_diary where activity_id = ").appendValue(activityId);
        return geliDao.count(sql.getSql(), sql.getValues());
    }

    /**
     * 删除同活动下的所有的原日记记录
     *
     * @param diaryId
     * @return
     */
    public int delDiaryByActivityId(long activityId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" delete from ac_activity_diary where activity_id = ? ");
        return jdbcTemplate.update(sql.getSql(), activityId);
    }

    /**
     * 根据日记ID获取对象
     *
     * @param diaryId
     * @return
     */
    public ActivityDiary getDiaryById(long diaryId) {
        if (diaryId < 1) {
            return null;
        }
        ActivityDiary diary = null;
        try {
            diary = geliDao.find(ActivityDiary.class, diaryId);
        } catch (DataAccessException e) {
            log.error("can't find activityDiary {}", diaryId);
        }
        return diary;
    }

    /**
     * 根据日记ID删除指定活动日记
     *
     * @param diaryId
     * @return
     */
    public boolean delDiaryByDiayId(ActivityDiary diary, long diaryId) {
        if (diary != null && diaryId > 0) {
            geliDao.delete(diary, diaryId);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据urls生成活动日记记录 接口返回null，方法返回-1 接口返回不为null，但result为null，则返回topicId
     * 接口返回result不为null：若diaryId>0 ，则更新数据，返回-2，否则增加数据，返回-3
     *
     * @param activityId
     * @param activityId2
     * @param urls
     * @return
     */
    public int addActivityDiary(ActivityDiary diary) {

        int retArr = 0;
        long topId;
        String url = diary.getTopicUrl();
        int begin = url.indexOf("-");
        int end = url.indexOf(".html");
        if (begin > 0 && end > 0) {
            try {
                topId = Long.parseLong(url.substring(begin + 1, end));
            } catch (NumberFormatException e) {

                log.error("id 转换出错,id=" + url.substring(begin + 1, end));
                return -1;
            }
        } else {
            log.error(url + "地址解析出错");
            return -1;
        }
        JSONArray jsonArr = null;
        if (topId > 0) {
            jsonArr = intfService.getBbsTxtJSON(topId);
        }
        if (jsonArr != null) {
            JSONObject object = jsonArr.getJSONObject(0);
            if (object.getString("result").equals("null")) {
                retArr = object.getInteger("topicId");
            } else if (diary.getDiaryId() < 1) {
                diary.setTopicId(object.getInteger("topicId"));
                diary.setTopicUrl(object.getString("topicUrl"));
                diary.setTitle(object.getString("title"));
                diary.setContent(object.getString("content"));
                diary.setTopicCover(object.getString("photourl"));
                diary.setSeq(1);
                diary.setDiaryCreate(object.getDate("createAt"));
                diary.setDiaryUpdate(DateUtils.getNow());
                diary.setCreateBy(object.getInteger("userId"));
                diary.setCreateName(object.getString("userName"));
                diary.setImage1Url(object.getString("image1"));
                diary.setImage2Url(object.getString("image2"));
                diary.setImage3Url(object.getString("image3"));

                long result = geliDao.create(diary);
                if (result > 0) {
                    retArr = -3;
                }
            } else if (diary.getDiaryId() > 0) {
                ActivityDiary activityDiary = geliDao.find(ActivityDiary.class, diary.getDiaryId());
                activityDiary.setTopicId(object.getInteger("topicId"));
                activityDiary.setTopicUrl(object.getString("topicUrl"));
                activityDiary.setTitle(object.getString("title"));
                activityDiary.setContent(object.getString("content"));
                activityDiary.setTopicCover(object.getString("photourl"));
                activityDiary.setDiaryCreate(object.getDate("createAt"));
                activityDiary.setDiaryUpdate(DateUtils.getNow());
                activityDiary.setCreateBy(object.getInteger("userId"));
                activityDiary.setCreateName(object.getString("userName"));
                long result = geliDao.update(activityDiary);
                // geliDao.update(activityDiary, "create_at");
                if (result > 0) {
                    retArr = -2;
                }
            }
        } else {
            log.error(topId + "数据返回为null");
            retArr = -1;
        }
        return retArr;
    }

    /**
     * 根据活动ID更新参加人员数
     *
     * @param activityId
     */
    public void refshActivityJoinNum(long activityId, long clubId) {

        if (activityId < 0) {
            return;
        }
        int total = 0;
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select id from ac_activity_member where activity_id = ").appendValue(activityId);
        sql.appendSql(" AND status=").appendValue(ActivityMember.STATUS_PASS);

        List<ActivityMember> listMember = geliDao.list(ActivityMember.class, sql.getSql(), sql.getValues());
        if (listMember != null && !listMember.isEmpty()) {
            for (ActivityMember member : listMember) {
                total += member.getJoinNum();
            }
        }

        Activity activity = geliDao.find(Activity.class, activityId);
        if (activity.getJoinNum() != total) {
            activity.setJoinNum(total);
            geliDao.update(activity, "join_num");
        }
    }

    /**
     * 新增活动后并添加日记时给车友会加10L油
     *
     * @param activityId 活动ID
     * @param isAdd 是否是加油
     * @param num 分值倍数
     */
    public void addOilToClub(long activityId, int num, boolean isAdd) {

        Activity activity = geliDao.find(Activity.class, activityId);
        if (activity != null && num > 0) {
            long clubId = activity.getClubId();
            if (clubId > 0) {
                int itemId;
                if (isAdd) {
                    //增加油值
                    itemId = PetrolService.ADD_CLUB_PETROL_ITEM_ACTIVITY;
                } else {
                    //减少油值
                    itemId = PetrolService.ADD_CLUB_PETROL_ITEM_ACTIVITY_DELETE;
                }
                ClubIntegral i = petrolService.getById(itemId);
                //日记通过积分限制给车友会加减分值
                petrolService.addToClubWithinLimit(clubId, (int) i.getIntegralId(), i.getPetrol() * num, i.getName(), true);
            }

        }
    }

    /**
     * 根据活动ID、板块ID检查数据， 如果存在，并且传入的topicId>0&&原先对象内的论坛id为0，则更新数据，返回"update"
     * 如果不存在，则创建，并返回结果"add"
     *
     * @param activityId
     * @param fomId
     * @return "update"/"add"/null
     */
    public String checkSynchronous(long activityId, long formumId, long topicId) {
        if (activityId < 1 || formumId < 1) {
            log.error("活动Id:" + activityId);
            log.error("论坛Id:" + formumId);
            return "error";
        }
        String result;
        SqlBuilder sql1 = new SqlBuilder();
        sql1.appendSql(" select id,activity_id,forum_id,topic_id from ").appendSql(geliOrm.getTableName(ActivityTopic.class));
        sql1.appendSql(" where activity_id = ").appendValue(activityId);
        sql1.appendSql(" and forum_id = ").appendValue(formumId);
        ActivityTopic activityTopic = geliDao.findFirst(ActivityTopic.class, sql1.getSql(), sql1.getValues());
        if (activityTopic != null) {
            if (topicId > 0) {
                result = "update";
                activityTopic.setTopicId(topicId);
                geliDao.update(activityTopic, "topic_id");
            } else {
                result = "add";
            }
        } else {
            result = "add";
            activityTopic = new ActivityTopic();
            activityTopic.setActivityId(activityId);
            activityTopic.setFormumId(formumId);
            geliDao.create(activityTopic);
        }
        return result;
    }

    /**
     * 根据活动查询论坛同步信息列表
     *
     * @param activityId
     * @return
     */
    public List<ActivityTopic> listActivityTopic(long activityId) {

        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select id from ").appendSql(geliOrm.getTableName(ActivityTopic.class));
        sql.appendSql(" where activity_id = ").appendValue(activityId);
        return geliDao.list(ActivityTopic.class, sql.getSql(), sql.getValues());
    }

    /**
     * 同步活动帖到BBS
     *
     * @param activity
     * @param content
     * @return
     */
    private String sendToBBS(Map<String, Object> params) {
        String bbsRoot = systemConfig.getBbsRoot();
        String result = simpleHttpTemplate.post(bbsRoot + "/util/poster.jsp", null, new ResponseExtractor<String>() {
            @Override
            public String extractData(HttpResponse response) throws IOException {
                StatusLine statusLine = response.getStatusLine();
                if (statusLine.getStatusCode() == 200) {
                    try {
                        return EntityUtils.toString(response.getEntity());
                    } catch (IOException ex) {
                        log.error("sendToBBS fail 1!", ex);
                    } catch (ParseException ex) {
                        log.error("sendToBBS fail 2!", ex);
                    }
                } else {
                    log.error("sendToBBS fail statusCode is " + statusLine.getStatusCode());
                    try {
                        log.error(EntityUtils.toString(response.getEntity()));
                    } catch (IOException ex) {
                        log.error("sendToBBS fail--IOException", ex);
                    } catch (ParseException ex) {
                        log.error("sendToBBS fail--ParseException", ex);
                    }
                }
                return "";
            }
        }, EntityBuilder.entity().params(params).build());

        return result;
    }

    /**
     * 根据ID删除活动
     *
     * @param activityId
     * @return
     */
    public int removeActivity(long activityId) {

        Activity activity = geliDao.find(Activity.class, activityId);
        activity.setStatus(Activity.STATUS_NO);
        int result = geliDao.update(activity, "status");
//		if(result >0){
//			//根据日记数量减分
//			int num = this.countDiayByActivityId(activityId);
//			if(num>0){
//				addOilToClub(activityId,num,false);
//			}
//		}
        return result;
    }

    /**
     * 删除活动超长内容
     *
     * @param activityId
     * @return
     */
    public int removeAcLongContext(long activityId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" delete from ").appendSql(geliOrm.getTableName(ActivityContext.class, activityId));
        sql.appendSql(" where activity_id = ? ");
        return jdbcTemplate.update(sql.getSql(), activityId);
    }

    /**
     * 取出车友会最新的前N条活动
     *
     * @param clubId
     * @return
     */
    public List<Activity> getNewActivity(long clubId, int num) {
        if (clubId < 1 || num < 1) {
            return null;
        }
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select activity_id from ").appendSql(geliOrm.getTableName(Activity.class));
        sql.appendSql(" where club_id =").appendValue(clubId);
        sql.appendSql(" and status =").appendValue(Activity.STATUS_YES);
        sql.appendSql(" order by create_at desc ");
        sql.appendSql(" limit 0," + num);
        List<Activity> list = null;
        try {
            list = geliDao.list(Activity.class, sql.getSql(), sql.getValues());
        } catch (DataAccessException e) {
        }
        return list;
    }

    /**
     * 根据车友会ID统计活动数量
     *
     * @param clubId
     * @return
     */
    public int countActivityByClubId(long clubId) {
        if (clubId < 1) {
            return 0;
        }
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select count(1) from ").appendSql(geliOrm.getTableName(Activity.class));
        sql.appendSql(" where club_id = ").appendValue(clubId);
        sql.appendSql(" and status = ").appendValue(Activity.STATUS_YES);
        return geliDao.count(sql.getSql(), sql.getValues());
    }

    /**
     * 根据id数组查询活动
     *
     * @param ids
     * @return
     */
    public List<Activity> listActivityByIds(String ids) {
        if (StringUtils.isBlank(ids)) {
            return null;
        }
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select activity_id from ").appendSql(geliOrm.getTableName(Activity.class));
        sql.appendSql(" where activity_id in (").appendSql(ids).appendSql(")");
        sql.appendSql(" and status = ").appendValue(Activity.STATUS_YES);
        sql.appendSql(" order by begin_date desc ");
        return geliDao.list(Activity.class, sql.getSql(), sql.getValues());
    }

    /**
     * 根据活动ID和会员ID获取报名信息
     *
     * @param targetId
     * @param activityId
     * @return
     */
    public ActivityMember getApplyByUidAid(long targetId, long activityId, int status) {

        if (targetId < 1 || activityId < 1) {
            return null;
        }
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select * from ").appendSql(geliOrm.getTableName(ActivityMember.class));
        sql.appendSql(" where user_id = ").appendValue(targetId);
        sql.appendSql(" and activity_id = ").appendValue(activityId);
        if (status != 99) {
            sql.appendSql(" and status = ").appendValue(status);
        }
        return geliDao.findFirst(ActivityMember.class, sql.getSql(), sql.getValues());
    }

    /**
     * 活动审核/拒绝
     *
     * @param type 1:审核通过 2:拒绝通过
     * @param member
     * @return
     */
    public boolean editApplyBy(int type, ActivityMember member, long clubId) {
        boolean result = false;
        if (type == ActivityMember.STATUS_PASS) {
            member.setStatus(ActivityMember.STATUS_PASS);
            geliDao.update(member, "status");
            result = true;
        } else if (type == ActivityMember.STATUS_DELETE) {
            geliDao.delete(member, member.getId());
            result = true;
        }
        if (result) {
            //更新活动已报名人数
            this.refshActivityJoinNum(member.getActivityId(), clubId);
        }
        return result;
    }

    public List<ActivityMember> listActivityAuditMembers(long activityId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select id from ").appendSql(geliOrm.getTableName(ActivityMember.class)).appendSql(" where activity_id=").appendValue(activityId).appendSql(" and status=0");
        List<ActivityMember> list = geliDao.list(ActivityMember.class, sql.getSql(), sql.getValues());
        return list;
    }

    /**
     * 根据会员ID和活动ID判断状态显示 TODO 可以参照OActivityService优化
     *
     * @param mid
     * @param activityId
     * @return
     */
    public Map<String, String> getListActivityStatus(long mid, Activity activity) {
        Map<String, String> map = new HashMap<String, String>();
        if (activity != null) {
            ActivityMember aMember = null;
            if (mid > 0) {
                aMember = this.getApplyByUidAid(mid, activity.getActivityId(), 99);
            }
            long nowDate = DateUtils.getNow().getTime();
            if (nowDate <= activity.getEndDate().getTime()) {
                if (aMember != null && aMember.getStatus() == ActivityMember.STATUS_PASS) {
                    map.put("msg", "已报名");
                    map.put("code", "203");
                } else {
                    if (activity.getBeginDate().getTime() <= activity.getSignupDate().getTime()) {
                        //报名人数是否上线
                        if ((activity.getMaxJoin() > 0 && activity.getJoinNum() < activity.getMaxJoin()) || activity.getMaxJoin() == 0) {
                            if (nowDate > activity.getSignupDate().getTime()) {
                                map.put("msg", "报名结束");
                                map.put("code", "103");
                            } else {
                                if (aMember != null && aMember.getStatus() == ActivityMember.STATUS_APPLY) {
                                    map.put("msg", "审核中");
                                    map.put("code", "201");
                                } else {
                                    map.put("msg", "火热报名");
                                    map.put("code", "101");
                                }
                            }
                        } else {
                            map.put("msg", "报名结束");
                            map.put("code", "102");
                        }
                    } else {
                        if (nowDate > activity.getBeginDate().getTime()) {
                            map.put("msg", "活动进行");
                            map.put("code", "104");
                        } else {
                            if (activity.getMaxJoin() > 0 && activity.getJoinNum() >= activity.getMaxJoin()) {
                                map.put("msg", "报名结束");
                                map.put("code", "102");
                            } else {
                                if (nowDate > activity.getSignupDate().getTime()) {
                                    map.put("msg", "报名结束");
                                    map.put("code", "103");
                                } else {
                                    if (aMember != null && aMember.getStatus() == ActivityMember.STATUS_APPLY) {
                                        map.put("msg", "审核中");
                                        map.put("code", "201");
                                    } else {
                                        map.put("msg", "火热报名");
                                        map.put("code", "101");
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                map.put("msg", "活动结束");
                map.put("code", "105");
            }
        } else {
            map.put("msg", "该活动不存在");
            map.put("code", "100");
        }
        return map;
    }

    public Map<String, String> getDetailActivityStatus(long mid, long activityId) {
        Map<String, String> map = new HashMap<String, String>();
        Activity activity = this.findById(activityId);
        if (activity != null) {
            ActivityMember aMember = null;
            if (mid > 0) {
                aMember = this.getApplyByUidAid(mid, activityId, 99);
            }
            long nowDate = DateUtils.getNow().getTime();
            if (nowDate <= activity.getEndDate().getTime()) {
                if (activity.getBeginDate().getTime() <= activity.getSignupDate().getTime()) {
                    if (nowDate > activity.getSignupDate().getTime()) {
                        map.put("msg", "报名已结束");
                        map.put("code", "103");
                    } else {
                        if (aMember != null && aMember.getStatus() == ActivityMember.STATUS_PASS) {
                            map.put("msg", "已报名");
                            map.put("code", "203");
                        } else if (activity.getMaxJoin() > 0 && activity.getJoinNum() >= activity.getMaxJoin()) {
                            map.put("msg", "报名已结束");
                            map.put("code", "102");
                        } else {
                            if (aMember != null && aMember.getStatus() == ActivityMember.STATUS_APPLY) {
                                map.put("msg", "审核中");
                                map.put("code", "201");
                            } else {
                                map.put("msg", "火热报名中");
                                map.put("code", "101");
                            }
                        }
                    }
                } else {
                    if (nowDate > activity.getBeginDate().getTime()) {
                        map.put("msg", "活动进行中");
                        map.put("code", "104");
                    } else {
                        if (aMember != null && aMember.getStatus() == ActivityMember.STATUS_PASS) {
                            map.put("msg", "已报名");
                            map.put("code", "203");
                        } else if (activity.getMaxJoin() > 0 && activity.getJoinNum() >= activity.getMaxJoin()) {
                            map.put("msg", "报名已结束");
                            map.put("code", "102");
                        } else {
                            if (nowDate > activity.getSignupDate().getTime()) {
                                map.put("msg", "报名已结束");
                                map.put("code", "103");
                            } else {
                                if (aMember != null && aMember.getStatus() == ActivityMember.STATUS_APPLY) {
                                    map.put("msg", "审核中");
                                    map.put("code", "201");
                                } else {
                                    map.put("msg", "火热报名中");
                                    map.put("code", "101");
                                }
                            }
                        }
                    }
                }
            } else {
                map.put("msg", "活动已结束");
                map.put("code", "105");
            }
        } else {
            map.put("msg", "该活动不存在");
            map.put("code", "100");
        }
        return map;
    }
    //获取该活动X状态下的报名人数
    //X:是否已经审核

    public int countActivityMemberByStatus(long activityId, int status) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select sum(join_num) from ").appendSql(geliOrm.getTableName(ActivityMember.class)).appendSql(" where activity_id = ").appendValue(activityId).appendSql(" and status=").appendValue(status);
        int count = geliDao.count(sql.getSql(), sql.getValues());
        return count;
    }
    
    /**
     * 判断用户是否有此活动的申请记录
     * @param activityId
     * @param userId
     * @return
     */
    public int countActivityMemberByActIdUserId(long activityId, long userId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select count(1) from ").appendSql(geliOrm.getTableName(ActivityMember.class)).appendSql(" where activity_id = ").appendValue(activityId).appendSql(" and user_id=").appendValue(userId);
        return geliDao.count(sql.getSql(), sql.getValues());
    }

    /**
     * 按指定顺序给出活动日记
     *
     * @param topicIds
     * @return
     */
    public List<ActivityDiary> getFirstDiaryByTopicIds(Object[] topicIds) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select diary_id from ").appendSql(geliOrm.getTableName(ActivityDiary.class));
        sql.appendSql(" where topic_id in ").appendValues(topicIds);
        sql.appendSql(" group by club_id,topic_id order by begin_at desc");
        try {
            List<ActivityDiary> list = geliDao.list(ActivityDiary.class, sql.getSql(), sql.getValues());
            List<ActivityDiary> nList = new ArrayList(list.size());
            for (Object idO : topicIds) {
                long id = (Long) idO;
                for (ActivityDiary a : list) {
                    if (id == a.getTopicId()) {
                        nList.add(a);
                    }
                }
            }
            return nList;
        } catch (EmptyResultDataAccessException e) {
            return Collections.emptyList();
        }
    }

    public Activity getLatestActivityByClub(long clubId) {
        Activity activity = new Activity();
        List<Activity> list = getNewActivity(clubId, 1);
        if (list != null && !list.isEmpty()) {
            activity = list.get(0);
        }
        return activity;
    }
    
    /**
     * 根据status获得活动报名人列表
     *
     * @param activityId
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Pager<ActivityMember> pageForApplyList(long activityId, int status, int pageNo, int pageSize) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select id from ").appendSql(geliOrm.getTableName(ActivityMember.class));
        sql.appendSql(" where activity_id =").appendValue(activityId);
        sql.appendSql(" and status = ").appendValue(status);
        Pager<ActivityMember> pager =  pagerService.pager(ActivityMember.class, sql, pageNo, pageSize);
        
        if (pager != null && !pager.getResultList().isEmpty()) {
            for (ActivityMember activitymember : pager.getResultList()) {
                if (activitymember.getUserId() > 0) {
                    ClubMember clubMember = memberService.find(activitymember.getUserId());
                    if (clubMember != null) {
                        activitymember.setUserPic(WebUtils.face(clubMember.getUid(), 50));
                        activitymember.setUserUrl(systemConfig.getUcRoot() + "/" + clubMember.getUid() + "/");
                        activitymember.setUserWapUrl(systemConfig.getUcRoot() + "/my/" + clubMember.getUid() + "/");
                        activitymember.setUser(userService.findUser(clubMember.getUid()));
                    }
                }
            }
        }
        
        return pager;
    }
    
    /**
     * 根据活动获取动态
     * @param activity
     * @return
     */
    public DynaInfo getDynaById(Activity activity){
    	if(activity==null) return null;
    	long targetId = activity.getActivityId();
    	int type = DynaInfo.TYPE_ACTIVITY;	//活动动态类型
    	Date createAt =activity.getCreateAt();
    	DynaInfo dynaInfo = dynaService.getDynaByTargetId(createAt, targetId, type );
    	return dynaInfo;
    }
}
